package steed.netty.serialization;

import java.util.List;

import org.json.JSONObject;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.ReplayingDecoder;
import steed.netty.module.BaseMsg;
import steed.netty.module.CommonMsg;
import steed.netty.module.LoginMsg;
import steed.netty.module.PingMsg;
import steed.util.base.BaseUtil;

public class JsonDecoder extends MessageToMessageDecoder<ByteBuf> {


	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
		byte[] msgByte = new byte[byteBuf.readableBytes()];
    	byteBuf.readBytes(msgByte);
    	String json = new String(msgByte);
    	BaseUtil.getLogger().debug("收到的数据{}",json);
    	JSONObject jsonObject = new org.json.JSONObject(json);
    	Class<? extends BaseMsg> target = CommonMsg.class;
    	if (jsonObject.has("userName")) {
			target  = LoginMsg.class;
		}else if (!jsonObject.has("msgCode")) {
    		target = PingMsg.class;
		}
    	BaseMsg msg = BaseUtil.parseJson(json, target);
    	String content = jsonObject.optString("content",null);
    	jsonObject.remove("content");
    	msg.setContent(content);
    	out.add(msg);
	}

}
